package 对递归问题的分析.day01;

/**
 * <Description>
 *
 * @author wangxi
 */
public class NumberOfIslands {

    public static void main(String[] args) {
        char[][] nums = {{'1','1','0','0','0'}, {'1','1','0','0','0'}, {'0','0','1','0','0'}, {'0','0','0','1','1'}};

        new NumberOfIslands().numIslands(nums);
    }

    // 时间复杂度O(N*N)，空间O(1)
    public int numIslands(char[][] grid) {
        if (grid == null || grid.length <= 0 || grid[0].length <= 0) {
            return 0;
        }
        int row = grid.length;
        int col = grid[0].length;
        int count = 0;
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (grid[i][j] == '2' || grid[i][j] == '0') {
                    continue;
                }
                dfs(grid, i, j, row, col);
                count++;
            }
        }
        return count;
    }

    private void dfs(char[][] grid, int i, int j, int row, int col) {
        if (i < 0 || i >= row || j < 0 || j >= col || grid[i][j]== '2' || grid[i][j]== '0') {
            return;
        }
        grid[i][j] = '2';
        dfs(grid, i + 1, j, row, col);
        dfs(grid, i - 1, j, row, col);
        dfs(grid, i, j - 1, row, col);
        dfs(grid, i, j + 1, row, col);
    }
}

